# encoding=UTF-8

import common as cm
import urllib2
import re


# 首次从网络获取所有历史记录
def first_fetch_all_history():
    code_list = cm.code_list_from_db()
    if code_list is None:
        print('[first_fetch_all_history] can not get code list from db')
        return

    for code in code_list:
        cm.save_history_to_db(code)


# 从网络补充获取所有历史记录
def append_fetch_all_history():
    code_list = cm.code_list_from_db()
    if code_list is None:
        print('[first_fetch_all_history] can not get code list from db')
        return

    for code in code_list:
        cm.append_web_history_to_db(code)


# 实时获取当前的数据
def recent_fetch_history(list):
    def enum_item_list(text):
        item_list = text.split(',')
        result = {
            'name': item_list[0],
            'open': item_list[1],
            'last_close': item_list[2],
            'current': item_list[3],
            'high': item_list[4],
            'low': item_list[5],
            'buy': item_list[6],
            'sold': item_list[7],
            'number': item_list[8],
            'time': item_list[30] + ' ' + item_list[31]
        }
        return result

    fix_list = map((lambda x:'sh'+x if x.startswith('6') else 'sz'+x), list)
    url = 'http://hq.sinajs.cn/list='+','.join(fix_list)
    text = urllib2.urlopen(urllib2.Request(url)).read().decode('gbk')
    count = len(list)
    s = 'var hq_str_.+="(.+)";\s*'*count
    pat = re.compile(s, re.MULTILINE)
    values = pat.findall(text)[0]
    if count > 1:
        if len(values) == count:
            result = {}
            for i, text in enumerate(values):
                code = list[i]
                result[code] = enum_item_list(text)
            return result
    elif count == 1:
        result = {}
        code = list[0]
        result[code] = enum_item_list(text)
        return result

    print('Can not get stock info')
    return None